package one.stand.controller;

import com.github.pagehelper.PageHelper;
import com.jmp.api.admin.dto.*;
import com.jmp.autocofiguration.web.interceptor.SecurityAuthCheck;
import com.jmp.base.TemplateApi;
import com.jmp.base.dto.TemplateDownRequest;
import com.jmp.base.dto.TemplatePreviewRequest;
import com.jmp.base.dto.TemplatePreviewResponse;
import com.jmp.base.dto.TemplateUpRequest;
import com.jmp.feign.TemplateFeign;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import one.stand.advice.ResultEnum;
import one.stand.dto.ConvertUtils;
import one.stand.dto.DictDto;
import one.stand.dto.PageResponse2;
import one.stand.mapper.CompanyApiAdminMapper;
import one.stand.mapper.TemplateApiAdminMapper;
import one.stand.model.CompanyCustomerLable;
import one.stand.model.ResultModel;
import one.stand.model.Template;
import one.stand.service.GoodsBaseService;
import one.stand.service.sys.SysDictValueService;
import one.stand.service.sys.UserContentService;
import one.stand.util.AssertUtil;
import one.stand.util.SqlUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

@Api("模板管理")
@RestController
@RequestMapping("adminApi/template")
@Slf4j
public class TemplateController {
    @Autowired
    private TemplateFeign templateFeign;

    @Autowired
    private SysDictValueService sysDictValueService;
    @Autowired
    private GoodsBaseService goodsBaseService;

    @Autowired
    private CompanyApiAdminMapper companyApiAdminMapper;
    @Autowired
    private TemplateApiAdminMapper templateApiAdminMapper;

    @ApiOperation("列表")
    @GetMapping("")
    @SecurityAuthCheck
    public ResultModel<TemplateListResponse> list(TemplateListRequest request) {

        String nameLike = SqlUtil.like(request.getName());
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<Template> templates = templateApiAdminMapper.selectByName(request.getType(),
                nameLike,
                request.getLabelId(),
                UserContentService.TYPE_CARD,
                TemplateApi.DEFAULT_COMPANYID);

        PageResponse2<TemplateListResponse.Template> list = ConvertUtils.page2(templates, template -> TemplateListResponse.Template.builder()
                .id(template.getId())
                .name(template.getName())
                .imgUrl(template.getImgUrl())
                .imgHtml(template.getImgHtml())
                .imgWidth(template.getImgWidth())
                .imgHeight(template.getImgHeight())
                .state(template.getState())
                .stateTime(Objects.nonNull(template.getStateTime()) ? DateFormatUtils.ISO_8601_EXTENDED_DATETIME_TIME_ZONE_FORMAT.format(template.getStateTime()) : null)
                .build());

        PageHelper.startPage(1, 100);// 100 标签应该不会超过100
        List<CompanyCustomerLable> labels = companyApiAdminMapper.selectLabel(TemplateApi.DEFAULT_COMPANYID, null);
        List<ArticleListResponse.Label> labelList = ConvertUtils.list(labels, label -> ArticleListResponse.Label.builder()
                .id(label.getLableId())
                .name(label.getLableName())
                .build());

        TemplateListResponse response = TemplateListResponse.builder()
                .templates(list)
                .labelList(labelList)
                .build();
        return ResultModel.success(response);
    }

    @ApiOperation("详情")
    @PostMapping("detail")
    @SecurityAuthCheck
    public ResultModel<TemplateDetailResponse> detail(@RequestBody TemplateDetailRequest request) {

        ResultModel<com.jmp.base.dto.TemplateDetailResponse> responseResultModel = templateFeign.detail(com.jmp.base.dto.TemplateDetailRequest.builder().templateId(request.getTemplateId()).build());
        AssertUtil.isTrue(responseResultModel);

        List<TemplateDetailResponse.Config> configList = ConvertUtils.list(responseResultModel.getData().getConfigs(), config -> TemplateDetailResponse.Config.builder()
                .type(config.getType())
                .pointX(config.getPointX())
                .pointY(config.getPointY())
                .imgWidth(config.getImgWidth())
                .imgHeight(config.getImgHeight())
                .imgUrl(config.getImgUrl())
                .fontStyle(config.getFontStyle())
                .fontSize(config.getFontSize())
                .fontCenter(config.getFontCenter())
                .fontColor(config.getFontColor())
                .build());

        TemplateDetailResponse response = TemplateDetailResponse.builder()
                .id(responseResultModel.getData().getId())
                .name(responseResultModel.getData().getName())
                .imgUrl(responseResultModel.getData().getImgUrl())
                .configs(configList)
                .build();

        return ResultModel.success(response);
    }

    @ApiOperation("保存")
    @PostMapping("save")
    @SecurityAuthCheck
    public ResultModel save(@RequestBody TemplateSaveRequest request) {

        com.jmp.base.dto.TemplateSaveRequest.Template template = com.jmp.base.dto.TemplateSaveRequest.Template.builder()
                .id(request.getId())
                .name(request.getName())
                .imgUrl(request.getImgUrl())
                .companyId(TemplateApi.DEFAULT_COMPANYID)
                .build();
        List<com.jmp.base.dto.TemplateSaveRequest.Config> configs = getConfig(request.getConfigs());

        ResultModel resultModel = templateFeign.save(com.jmp.base.dto.TemplateSaveRequest.builder()
                .template(template)
                .templateConfigs(configs)
                .build());
        AssertUtil.isTrue(resultModel);

        return ResultModel.success();
    }

    @ApiOperation("预览")
    @PostMapping("preview")
    @SecurityAuthCheck
    public ResultModel<String> preview(@RequestBody TemplateSaveRequest request) {

        com.jmp.base.dto.TemplateSaveRequest.Template template = com.jmp.base.dto.TemplateSaveRequest.Template.builder()
                .imgUrl(request.getImgUrl())
                .build();
        List<com.jmp.base.dto.TemplateSaveRequest.Config> configs = getConfig(request.getConfigs());

        DictDto cardDict = sysDictValueService.get2(SysDictValueService.Type.CONFIG_TEMPLATE, SysDictValueService.TypeNameTemplate.PREVIEW_CARD_ID.name());
        DictDto goodsDict = sysDictValueService.get2(SysDictValueService.Type.CONFIG_TEMPLATE, SysDictValueService.TypeNameTemplate.PREVIEW_GOODS_ID.name());
        DictDto articleDict = sysDictValueService.get2(SysDictValueService.Type.CONFIG_TEMPLATE, SysDictValueService.TypeNameTemplate.PREVIEW_ARTICLE_ID.name());
        DictDto diyDict = sysDictValueService.get2(SysDictValueService.Type.CONFIG_TEMPLATE, SysDictValueService.TypeNameTemplate.PREVIEW_DIY_URL.name());
        DictDto liveRoomDict = sysDictValueService.get2(SysDictValueService.Type.CONFIG_TEMPLATE, SysDictValueService.TypeNameTemplate.PREVIEW_ROOM_ID.name());
        DictDto groupDict = sysDictValueService.get2(SysDictValueService.Type.CONFIG_TEMPLATE, SysDictValueService.TypeNameTemplate.PREVIEW_GROUP_ID.name());
        DictDto articleH5Dict = sysDictValueService.get2(SysDictValueService.Type.CONFIG, SysDictValueService.TypeNameConfig.article_h5.name());
        String groupPrice = "12.20";
        TemplatePreviewRequest previewRequest = TemplatePreviewRequest.builder()
                .template(template)
                .configs(configs)
                .cardId(cardDict.getValueInteger())
                .goodsId(goodsDict.getValueInteger())
                .articleId(articleDict.getValueInteger())
                .roomId(liveRoomDict.getValueInteger())
                .groupId(groupDict.getValueInteger())
                .diyUrl(diyDict.getValue())
                .articleH5Url(String.format(articleH5Dict.getValue(), articleDict.getValueInteger(), cardDict.getValueInteger()))
                .groupPrice(groupPrice)
                .groupH5Url(goodsBaseService.getGroupShareH5Url(cardDict.getValueInteger(), groupDict.getValueInteger(), groupPrice))
                .build();
        ResultModel<TemplatePreviewResponse> previewResponseResultModel = templateFeign.preview(previewRequest);
        AssertUtil.isTrue(previewResponseResultModel);

        String url = previewResponseResultModel.getData().getImageUrl();

        return ResultModel.success(url);
    }

    @ApiOperation("发布或下架")
    @PostMapping("update")
    @SecurityAuthCheck
    public ResultModel update(@RequestBody TemplateUpdateRequest request) {

        ResultModel resultModel;
        if (request.getState() == TemplateApi.STATE_DEPLOY) {
            String labels = StringUtils.join(request.getLabels(), ",");
            resultModel = templateFeign.up(TemplateUpRequest.builder()
                    .id(request.getId())
                    .pushTitle(request.getPushTitle())
                    .pushContent(request.getPushContent())
                    .labels(labels)
                    .build());
        } else {
            resultModel = templateFeign.down(TemplateDownRequest.builder().id(request.getId()).build());
        }
        AssertUtil.isTrue(resultModel);

        return ResultModel.success();
    }

    @ApiOperation("清除")
    @PostMapping("remove")
    @SecurityAuthCheck
    public ResultModel remove(@RequestBody TemplateRemoveRequest request) {

        AssertUtil.isTrue(Objects.nonNull(request.getCompanyId()) || Objects.nonNull(request.getCardId()), ResultEnum.PARAM_CHECK);
        templateApiAdminMapper.deleteByCard(request.getCompanyId(), request.getCardId());

        return ResultModel.success();
    }

    private List<com.jmp.base.dto.TemplateSaveRequest.Config> getConfig(List<TemplateSaveRequest.Config> configs) {
        return ConvertUtils.list(configs, config -> {
            com.jmp.base.dto.TemplateSaveRequest.Config templateConfig = com.jmp.base.dto.TemplateSaveRequest.Config.builder()
                    .type(config.getType())
                    .pointX(config.getPointX())
                    .pointY(config.getPointY())
                    .imgWidth(config.getImgWidth())
                    .imgHeight(config.getImgHeight())
                    .imgUrl(config.getImgUrl())
                    .fontStyle(config.getFontStyle())
                    .fontSize(config.getFontSize())
                    .fontCenter(config.getFontCenter())
                    .fontColor(config.getFontColor())
                    .build();
            return templateConfig;
        });
    }
}
